<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const PENDING = "PENDING", SUCCESS = 'SUCCESS', REJECT = "REJECT"
        class CPromise {
            status = PENDING
            callbacks = [];
            errorCallbacks = [];
            val;
            err;
            constructor(func) {
                const resolve = (val) => {
                    this.status = SUCCESS;
                    this.val = val;
                    this.callbacks.forEach(cb => cb());
                }
                const reject = (err) => {
                    this.status = REJECT;
                    this.err = err;
                    this.errorCallbacks.forEach(cb => cb())
                }
                func(resolve, reject)
            }
            then(callback, errback) {
                this.callbacks.push(() => callback(this.val))
                if(this.status === SUCCESS) {
                    this.callbacks.forEach(cb => cb());
                }
                errback && this.errorCallbacks.push(() => errback(this.err))
                if(this.status === REJECT) {
                    this.errorCallbacks.forEach(cb => cb())
                }
            }
            
            
        }
        const p = new CPromise(function(resolve, reject) {
            setTimeout(() => {
                resolve(5);
            }, 3000)
            // resolve(30)
        })
        p.then(res => console.log(res))
    </script>
</body>
</html>